<?php

namespace app\common\model\factory;

use think\Db;
use think\Model;


class Sales extends Model
{

    

    

    // 表名
    protected $name = 'factory_sales';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'deliverytime_text'
    ];
    public function slip_status(){
        return array(
            1=>'代采购',
            2=>'待审核',
            3=>'待发货',
            4=>'待收货',
            5=>'已完成',
            6=>'驳回',
            7=>'强制中止',
            8=>'关闭',
        );
    }

    //检测是否完成任务
    public function checkstatus($slip_id){
        $goods = new Goods();
        //销售单总数量
        $gnum = $goods->where(array('sales_slip_id' => $slip_id))->sum('goods_num');

        //出库单总量
        $succnum =Db::name('sales_checkout_goods')
                ->alias('cg')
                ->join('sales_checkout c','cg.sales_checkout_id = c.id')
                ->where(array('cg.sales_slip_id' =>$slip_id,'cg.status'=>1))
                ->sum('goods_num');

        if($succnum == $gnum){
            $res = Db::name('sales_slip')->where(array('id'=>$slip_id))->update(array('status'=>5));
            if(!$res){
                return false;
            }
        }
        return  true;
    }



    public function getDeliverytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['deliverytime']) ? $data['deliverytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setDeliverytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
